<?php

namespace App\Models;

use App\Admin\Traits\AdminBuilder;
use App\Admin\Traits\ModelTree;
use App\Admin\Traits\CanValidate;
use Illuminate\Database\Eloquent\Model;
use QrCode;

class Lotto extends Model
{
    use CanValidate;
    use AdminBuilder;

    protected $fillable = ['title', 'bg_image', 'settings', 'bg_music', 'valid'];

    public function validateRules()
    {
        return [
            'title'             => 'required|max:255',
            'valid'             => 'nullable|boolean',
            'settings'          => 'required|array|min:1',
            'settings.*.name'   => 'required|max:10',
            'settings.*.number' => 'nullable|integer|min:1',
            'settings.*.desc'   => 'nullable|max:50',
        ];
    }

    public function validateMessages()
    {
        return [
            'valid.*' => ':attribute选择无效',
        ];
    }

    public function validateAttributes()
    {
        return [
            'title'             => '标题',
            'settings.*.name'   => '奖项名',
            'settings.*.number' => '默认人数',
            'settings.*.desc'   => '说明',
            'settings'          => '奖项设置',
            'valid'             => '是否开启',
        ];
    }

    public function setSettingsAttribute($value)
    {
        $this->attributes['settings'] = json_encode(array_values($value));
    }

    public function getSettingsAttribute($value)
    {
        return json_to_array($value);
    }

    public function players()
    {
        return $this->belongsToMany(User::class, 'lotto_players')->withPivot('created_at', 'award')->withTimestamps();
    }

    public function joinLink()
    {
        return route('lottos.join', $this);
    }

    public function joinQrCode($size = 1000)
    {
        return 'data:image/png;base64, '
            .base64_encode(
                QrCode::format('png')
                      ->size($size)
                      ->margin(1)
                      ->generate($this->joinLink())
            );
    }
}
